# -*- coding: utf-8 -*-

from ldap3 import Server, Connection, ALL, SUBTREE, ServerPool

LDAP_SERVER_POOL = ["10.39.95.5","10.39.95.6"]
LDAP_SERVER_PORT = 389
ADMIN_DN = "administrator"
ADMIN_PASSWORD = "Qdingnet@2018"
SEARCH_BASE = "ou=千丁互联,dc=qdingnet,dc=cn"


def ldap_auth(username, password):
    ldap_server_pool = ServerPool(LDAP_SERVER_POOL)
    conn = Connection(ldap_server_pool, user=ADMIN_DN, password=ADMIN_PASSWORD, check_names=True, lazy=False, raise_exceptions=False)
    conn.open()
    conn.bind()

    res = conn.search(
        search_base = SEARCH_BASE,
        search_filter = '(sAMAccountName={})'.format(username),
        # search_filter = '(sAMAccountName=sungaohui)',
        # search_filter = '(department=运维中心)',
        # search_filter = '(ou=技术研发部)',
        search_scope = SUBTREE,
        attributes = ['department', 'mail', 'sAMAccountName','telephoneNumber','displayName','title'],
        # paged_size = 100
    )

    if res:
        entry = conn.response[0]
        print(entry)
        group_sets = set()
        # for i in entry:
            # print(i)
            # print(type(i))
            # print(i["raw_attributes"]["department"])
            # attr_dict = i['attributes']
            # print(attr_dict)
            # if not i["raw_attributes"]["department"]:
            #     print(111)
            # else:
            #     # print(i["raw_attributes"]["department"][0].decode('utf-8'))
            #     print(attr_dict['department'])
            #     group_sets.add(attr_dict['department'])
            # print(group_sets)
            # for i in entry:
        dn = entry['dn']
        attr_dict = entry['attributes']

        print("sss",entry)
        print("sss",dn)
        print("sss",attr_dict)

        # check password by dn
        try:
            conn2 = Connection(ldap_server_pool, user=dn, password=password, check_names=True, lazy=False, raise_exceptions=False)
            conn2.bind()
            if conn2.result["description"] == "success":
                print(2222)
                print(conn2.result)
                print(True, attr_dict["sAMAccountName"])
                # return (True, attr_dict["mail"], attr_dict["sAMAccountName"], attr_dict["givenName"])
                return (True, attr_dict["sAMAccountName"])
            else:
                print("auth fail")
                return (False, None)
        except Exception as e:
            print("auth fail")
            return (False, None)
    else:
        return (False, None)


# if __name__ == "__main__":
#     ldap_auth("sungaohui", "!QAZ2wsx")